<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />

    <!-- 表单 -->
    <!-- submit：就是提交的事件,一定要全部验证通过才会调用 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="obj.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="obj.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          loading-text="正在登录中..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 控制按钮的加载状态
      isLoading: false,
      obj: {
        mobile: "13800138002",
        code: "246810",
      },

      rules: {
        mobile: [
          { required: true, message: "请填写手机号" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
        ],

        code: [
          { required: true, message: "请填写验证码" },
          { pattern: /^\d{6}$/, message: "请填写6位数字验证码" },
        ],
      },
    };
  },
  methods: {
    async onSubmit() {
      // 把加载状态改成true
      this.isLoading = true;
      try {
        // 发请求做登录
        // 我们的接口特点：如果登录成功不报错
        // 登录失败会报错，报错就进入到catch里
        let res = await this.$axios({
          url: "/v1_0/authorizations",
          method: "post",
          data: {
            mobile: this.obj.mobile,
            code: this.obj.code,
          },
        });
        this.$toast.success("登录成功！");

        // 把数据保存到vuex
        this.$store.commit('setToken', res.data.data)

        // 跳转
        this.$router.push('/layout/home')

      } catch {

        this.$toast.fail("登录失败！");

      }finally {

        this.isLoading = false
      }
    },
  },
};
</script>

<style>
</style>